<template>
  <div style="padding: 20px; max-width: 600px; margin: 0 auto;">
    <h2>图片上传测试 (/product/uploadImages)</h2>
    
    <div style="margin: 20px 0;">
      <label for="file-input" style="display: block; margin-bottom: 10px;">选择图片文件：</label>
      <input 
        id="file-input"
        type="file" 
        accept="image/*"
        @change="handleFileChange"
        style="margin-bottom: 10px;"
      />
      
      <button 
        @click="uploadImage" 
        :disabled="!selectedFile || uploading"
        style="padding: 8px 16px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;"
      >
        {{ uploading ? '上传中...' : '上传图片' }}
      </button>
    </div>

    <div v-if="errorMessage" style="color: red; margin: 10px 0;">
      错误: {{ errorMessage }}
    </div>

    <div v-if="imageUrl" style="margin: 20px 0;">
      <h3>上传成功！返回的URL:</h3>
      <p style="word-break: break-all; background: #f5f5f5; padding: 10px; border-radius: 4px;">
        {{ imageUrl }}
      </p>
      
      <h3>图片预览:</h3>
      <img 
        :src="imageUrl" 
        alt="上传的图片" 
        style="max-width: 100%; height: auto; border: 1px solid #ddd; border-radius: 4px;"
        @error="handleImageError"
      />
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { uploadProductImage } from '@/api/user'

export default {
  name: 'TestUploadImage',
  setup() {
    const selectedFile = ref(null)
    const uploading = ref(false)
    const imageUrl = ref('')
    const errorMessage = ref('')

    const handleFileChange = (event) => {
      selectedFile.value = event.target.files[0]
      // 清除之前的结果
      imageUrl.value = ''
      errorMessage.value = ''
    }

    const uploadImage = async () => {
      if (!selectedFile.value) {
        errorMessage.value = '请先选择文件'
        return
      }

      uploading.value = true
      errorMessage.value = ''

      try {
        const response = await uploadProductImage(selectedFile.value)
        console.log('上传响应:', response)
        
        // 假设后端直接返回URL字符串
        imageUrl.value = response
      } catch (error) {
        console.error('上传失败:', error)
        errorMessage.value = error.message || '上传失败'
      } finally {
        uploading.value = false
      }
    }

    const handleImageError = () => {
      errorMessage.value = '图片加载失败，请检查返回的URL是否正确'
    }

    return {
      selectedFile,
      uploading,
      imageUrl,
      errorMessage,
      handleFileChange,
      uploadImage,
      handleImageError
    }
  }
}
</script>